﻿using System.Diagnostics.Contracts;

namespace Hippo.Common.Extensions
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public static class EnumerableExtensions
    {
        public static string ToDelimitedString<T>(this IEnumerable<T> list, string separator)
        {
            return ToDelimitedString(list, separator, DefaultConverter);
        }

        public static string ToDelimitedString<T>(this IEnumerable<T> list, string separator, Converter<T, string> converter)
        {
            // List can't be null  
            if (list == null)
            {
                throw new ArgumentNullException("list", "Tried to create a string from a list that was null");
            }

            if (separator == null)
            {
                throw new ArgumentNullException("separator", "Must specify a separator even if it is string.Empty");
            }
            Contract.EndContractBlock();

            // If converter was null, we probably wanted default converter  
            if (converter == null)
            {
                return list.ToDelimitedString(separator, DefaultConverter);
            }

            // Start the process of creating the string  
            var sb = new StringBuilder();
            foreach (var o in list)
            {
                sb.Append(converter(o));
                sb.Append(separator);
            }

            /* Remove last seperator (if there is one) */
            if (sb.Length > 0)
            {
                sb.Length -= separator.Length;
            }

            return sb.ToString();
        }

        private static string DefaultConverter<T>(T item)
        {
            return item.ToString();
        }
    } 
}
